/*
 * WaveNotificatorView.java
 */
package wavenotificator;

import java.awt.AWTException;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.MenuShortcut;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JDialog;
import javax.swing.JFrame;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 * The application's main frame.
 */
public class WaveNotificatorView extends FrameView implements ActionListener {

    private static final String SETTINGS_DIR=".wavenotificator";
    private static final String SETTINGS_FILE="wavenotificator.properties";

    public WaveNotificatorView(SingleFrameApplication app) {
        super(app);

        initComponents();

        initSystemTray();

        postInit();

        // status bar initialization - message timeout, idle icon and busy animation, etc


    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = WaveNotificatorApp.getApplication().getMainFrame();
            aboutBox = new WaveNotificatorAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        WaveNotificatorApp.getApplication().show(aboutBox);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        loginTextField = new javax.swing.JTextField();
        rememberCheckBox = new javax.swing.JCheckBox();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        passwordField = new javax.swing.JPasswordField();
        errorLabel = new javax.swing.JLabel();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        popupMenu1 = new java.awt.PopupMenu();
        menuItem1 = new java.awt.MenuItem();

        mainPanel.setName("mainPanel"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(wavenotificator.WaveNotificatorApp.class).getContext().getResourceMap(WaveNotificatorView.class);
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        loginTextField.setText(resourceMap.getString("loginTextField.text")); // NOI18N
        loginTextField.setName("loginTextField"); // NOI18N

        rememberCheckBox.setText(resourceMap.getString("rememberCheckBox.text")); // NOI18N
        rememberCheckBox.setName("rememberCheckBox"); // NOI18N

        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(wavenotificator.WaveNotificatorApp.class).getContext().getActionMap(WaveNotificatorView.class, this);
        jButton2.setAction(actionMap.get("quit")); // NOI18N
        jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N
        jButton2.setName("jButton2"); // NOI18N

        passwordField.setText(resourceMap.getString("passwordField.text")); // NOI18N
        passwordField.setName("passwordField"); // NOI18N

        errorLabel.setForeground(resourceMap.getColor("errorLabel.foreground")); // NOI18N
        errorLabel.setText(resourceMap.getString("errorLabel.text")); // NOI18N
        errorLabel.setName("errorLabel"); // NOI18N

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(loginTextField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 261, Short.MAX_VALUE)
                            .addComponent(rememberCheckBox)
                            .addComponent(passwordField, javax.swing.GroupLayout.DEFAULT_SIZE, 261, Short.MAX_VALUE)))
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addComponent(errorLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 222, Short.MAX_VALUE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton2)))
                .addContainerGap())
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addGap(25, 25, 25)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(loginTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(18, 18, 18)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(passwordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(rememberCheckBox)
                .addGap(18, 18, 18)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton1)
                    .addComponent(errorLabel))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setAction(actionMap.get("quit")); // NOI18N
        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        exitMenuItem.setText(resourceMap.getString("exitMenuItem.text")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        popupMenu1.setLabel(resourceMap.getString("popupMenu1.label")); // NOI18N

        menuItem1.setLabel(resourceMap.getString("menuItem1.label")); // NOI18N
        menuItem1.setShortcut(new MenuShortcut(KeyEvent.VK_X, false));
        menuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuItem1ActionPerformed(evt);
            }
        });
        popupMenu1.add(menuItem1);

        setComponent(mainPanel);
        setMenuBar(menuBar);
    }// </editor-fold>//GEN-END:initComponents

    private void menuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItem1ActionPerformed
        System.exit(0);
    }//GEN-LAST:event_menuItem1ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        if (login()) {
//        cleanPanel();
//        refreshPanel();
            this.getFrame().setVisible(false);
            Timer timer = new Timer();
            timer.schedule(new RefreshTask(), 0, 5 * 60 * 1000);

            if(rememberCheckBox.isSelected()){
                settings.setProperty("user.login", loginTextField.getText());
                settings.setProperty("user.password", new String(passwordField.getPassword()));
                settings.setProperty("remember.me", "true");
            }else{
                settings.remove("user.login");
                settings.remove("user.password");
                settings.remove("remember.me");
            }
            saveSettings();
        } else {
            errorLabel.setText(errorMsg);
        }
    }//GEN-LAST:event_jButton1ActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel errorLabel;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JTextField loginTextField;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private java.awt.MenuItem menuItem1;
    private javax.swing.JPasswordField passwordField;
    private java.awt.PopupMenu popupMenu1;
    private javax.swing.JCheckBox rememberCheckBox;
    // End of variables declaration//GEN-END:variables
    private JDialog aboutBox;
    private TrayIcon trayIcon;
    private String loginToken;
    private String errorMsg;
    private Collection<MenuItem> wavesList = new ArrayList<MenuItem>();
    private Properties settings=new Properties();

    private void initSystemTray() {
        if (SystemTray.isSupported()) {
            ResourceMap resourceMap = getResourceMap();
            SystemTray systemTray = SystemTray.getSystemTray();
            URL imageUrl = getClass().getResource(resourceMap.getString("tray.icon"));
            Image image = Toolkit.getDefaultToolkit().getImage(imageUrl);

            trayIcon = new TrayIcon(image, resourceMap.getString("tray.tooltip"), popupMenu1);
            trayIcon.setImageAutoSize(true);

            ActionListener actionListener = new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    cleanPanel();
                    refreshPanel();
                }
            };


            trayIcon.addActionListener(actionListener);

            try {
                systemTray.add(trayIcon);
            } catch (AWTException ex) {
                Logger.getLogger(WaveNotificatorView.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    }

    private void postInit(){
        getFrame().setResizable(false);
        loadSettings();
        String login=settings.getProperty("user.login");
        if(login!=null){
            loginTextField.setText(login);
        }
        String password=settings.getProperty("user.password");
        if(password!=null){
            passwordField.setText(password);
        }
        String rememberMe=settings.getProperty("remember.me");
        if(rememberMe!=null){
            rememberCheckBox.setSelected(true);
        }
    }

    private void refreshPanel() {
        try {
            final String url = "https://wave.google.com/wave/?nouacheck&auth=" + URLEncoder.encode(loginToken.trim(), "UTF-8");
            HttpGet inbox = new HttpGet(url);
            inbox.setHeader("User-Agent", "Google Wave Add-on for Firefox");
            final DefaultHttpClient client = new DefaultHttpClient();
            final HttpResponse execute = client.execute(inbox);
            final BufferedReader br = new BufferedReader(new InputStreamReader(execute.getEntity().getContent(), "UTF-8"));
            String line = null;
            Pattern compile = Pattern.compile(".*(\\{\"r\":\"\\^d1.*\\});.*");
            int count = 0;
            while ((line = br.readLine()) != null) {
                final Matcher matcher = compile.matcher(line);
                final boolean isMatch = matcher.matches();
                if (isMatch) {
                    final JSONObject object = new JSONObject(matcher.group(1));
                    JSONObject inb = object.getJSONObject("p");
                    final JSONArray inboxArray = inb.getJSONArray("1");
                    for (int i = 0; i < inboxArray.length(); i++) {
                        final JSONObject element = inboxArray.getJSONObject(i);
                        String readMe = element.getString("7");
                        final String str = element.getJSONObject("9").getString("1");
                        if (str != null && str.trim().length() > 0) {
                            MenuItem item = new MenuItem(readMe + " | " + str);
                            item.addActionListener(this);
                            popupMenu1.add(item);
                            wavesList.add(item);
                            try{
                                count+=Integer.valueOf(readMe);
                            }catch(Exception e){
                            }
                        }
                    }
                }
            }
            if(count>0)
                trayIcon.displayMessage("Google Wave Notificator", "You have " + count + " unreaded messages", TrayIcon.MessageType.INFO);
        } catch (Exception ex) {
            Logger.getLogger(WaveNotificatorView.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private boolean login() {
        try {
            String line = URLEncoder.encode("accountType", "UTF-8") + "=" + URLEncoder.encode("GOOGLE", "UTF-8");
            line += "&" + URLEncoder.encode("Email", "UTF-8") + "=" + URLEncoder.encode(loginTextField.getText(), "UTF-8");
            line += "&" + URLEncoder.encode("Passwd", "UTF-8") + "=" + URLEncoder.encode(new String(passwordField.getPassword()), "UTF-8");
            line += "&" + URLEncoder.encode("service", "UTF-8") + "=" + URLEncoder.encode("wave", "UTF-8");
            line += "&" + URLEncoder.encode("source", "UTF-8") + "=" + URLEncoder.encode("com.calms.gwave.GWaveNotifier", "UTF-8");
            line += "\n";
            HttpPost httpPost = new HttpPost("https://www.google.com/accounts/ClientLogin");
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
            httpPost.setEntity(new StringEntity(line));
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpResponse httpResponse = httpClient.execute(httpPost);
            BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
            String respText = "";

            for (String row = reader.readLine(); row != null; row = reader.readLine()) {
                respText += row + "\n";
            }
            System.out.println(respText);
            if (respText.contains("Auth=")) {
                loginToken = respText.split("Auth=")[1];
                return true;
            }
            errorMsg = "Bad authentication";
        } catch (Exception ex) {
            Logger.getLogger(WaveNotificatorView.class.getName()).log(Level.SEVERE, null, ex);
        }
        return false;
    }

    private void cleanPanel() {
        for (MenuItem mi : wavesList) {
            popupMenu1.remove(mi);
        }
        wavesList.clear();
    }

    public void actionPerformed(ActionEvent e) {
        java.awt.Desktop desktop = java.awt.Desktop.getDesktop();
        if (desktop.isSupported(java.awt.Desktop.Action.BROWSE)) {
            try {
                desktop.browse(new URI("http://wave.google.com"));
            } catch (Exception ex) {
                Logger.getLogger(WaveNotificatorView.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    private class RefreshTask extends TimerTask {

        @Override
        public void run() {
            WaveNotificatorView.this.cleanPanel();
            WaveNotificatorView.this.refreshPanel();
        }
    }

    private void loadSettings(){
        String userHome=System.getProperty("user.home");
        File dir=new File(userHome, SETTINGS_DIR);
        if(dir.exists() && dir.isDirectory()){
            File settingsFile=new File(dir, SETTINGS_FILE);
            if(settingsFile.exists() && settingsFile.isFile()){
                try {
                    settings.load(new FileInputStream(settingsFile));
                } catch (IOException ex) {
                    Logger.getLogger(WaveNotificatorView.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    private void saveSettings(){
        String userHome=System.getProperty("user.home");
        File dir=new File(userHome, SETTINGS_DIR);
        if(!dir.exists()){
            dir.mkdir();
        }
        File settingsFile=new File(dir, SETTINGS_FILE);
        try {
            settings.store(new FileOutputStream(settingsFile), "Wave notificator settings");
        } catch (IOException ex) {
            Logger.getLogger(WaveNotificatorView.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
